import os
import pathlib
import pandas as pd
import sys
import unittest

cyphersearch_path = (pathlib.Path(os.path.abspath(__file__)).parent.parent.parent.parent / 
                        'shell' / 
                        'knowledge_graph')
sys.path.append(str(cyphersearch_path))
import cypher_search

class CypherSearchTest(unittest.TestCase):

    @classmethod
    def setUpClass(self) -> None:
        test_excel_file = (pathlib.Path(os.path.abspath(__file__)).parent.parent.parent.parent / 
                            'etc' / 
                            'nodes_relation.xlsx')
        test_sheet_name = 'cypher'
        self.__test_df = pd.read_excel(test_excel_file, sheet_name=test_sheet_name)
        self.__cyphersearch = cypher_search.CypherSearch(test_excel_file)
    
    def test_excelcase(self) -> None:
        for i, row in self.__test_df.iterrows():
            node1 = {'table': row[0], 'attr': 'node1_attr', 'value': 'node1_value', 
                        'is_attr':'node1_is_attr'}
            node2 = {'table': row[1], 'attr': 'node1_attr', 'value': 'node1_value', 
                        'is_attr':'node1_is_attr'}
            map_dict = {"node1_attr": node1['attr'],'node1_value': node1['value'],
                         'node2_attr': node2['attr']}
            cypher = row[2].format_map(map_dict)

            testitem = f"node1: {row[0]}, node2: {row[1]}, cypher: {cypher}"
            with self.subTest(testitem=testitem):
                self.assertEqual(self.__cyphersearch.template_match(node1, node2), cypher)

    def test_samenodes(self) -> None:
        node1 = {'table': 'node', 'attr': 'attr', 'value': 'value', 'is_attr':'is_attr'}
        node2 = {'table': 'node', 'attr': 'attr', 'value': 'value', 'is_attr':'is_attr'}
        cypher = "match (n:{}) where n.{}='{}' return n.{}".format(node1['table'], 
                    node1['attr'], node1['value'], node2['attr'])
        self.assertEqual(self.__cyphersearch.template_match(node1, node2), cypher)


if __name__ == '__main__':
    suite = unittest.TestSuite()
    suite.addTests(unittest.TestLoader().loadTestsFromTestCase(CypherSearchTest))

    resultfile = pathlib.Path(os.path.dirname(__file__)) / (__file__.split('.')[0] + '.report')
    with open(resultfile, 'w', encoding='utf8') as f:
        runner = unittest.TextTestRunner(stream=f, verbosity=2)
        runner.run(suite)
